package com.jy.appmarket.activity;

import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Point;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.webkit.URLUtil;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.github.johnpersano.supertoasts.SuperActivityToast;
import com.github.johnpersano.supertoasts.SuperToast;
import com.github.johnpersano.supertoasts.util.OnClickWrapper;
import com.jy.appmarket.AppMarketApplication;
import com.jy.appmarket.R;
import com.jy.appmarket.download.DownloadActivity;
import com.jy.appmarket.download.DownloadService;
import com.jy.appmarket.download.DownloadUtils;
import com.jy.appmarket.receiver.PushReceiver;
import com.jy.appmarket.utils.ActivateStatistics;
import com.jy.appmarket.utils.AppLinkParser;
import com.jy.appmarket.utils.LocationUtil;
import com.jy.appmarket.utils.LogUtil;
import com.jy.appmarket.utils.NetTools;
import com.jy.appmarket.utils.PackageUtils;
import com.umeng.analytics.MobclickAgent;

public class WebViewActivity extends DownloadActivity implements OnClickListener {
	private static final String TAG = WebViewActivity.class.getSimpleName();
	public static final String EXTRA_URL = "extra_url";
	public static final String EXTRA_TITLE = "extra_title";
	public static final String EXTRA_PUSHID = "extra_pushId";

	private String mInitUrl;
	private String mTitle;
	private WebView mWebView;
	private ProgressBar mProgressbar;
	private View mErrorView;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.web_view_layout);
		getExtras();
		initTitle();
		initView();
		initContent();
		ActivateStatistics.ActivateFrom(this, this.getClass().getSimpleName());
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mWebView.destroy();
	}

	private void getExtras() {
		if (getIntent() == null) {
			return;
		}
		mInitUrl = getIntent().getStringExtra(EXTRA_URL);
		mTitle = getIntent().getStringExtra(EXTRA_TITLE);
		String pushId = getIntent().getStringExtra(EXTRA_PUSHID);
		if (pushId != null) {
			PushReceiver.sendConsumeBroadcast(this, pushId, 0);
		}
	}

	private void initTitle() {
		ActionBar actionBar = getActionBar();
		if (!TextUtils.isEmpty(mTitle)) {
			actionBar.setTitle(mTitle);
		} else {
			actionBar.setTitle(R.string.app_name);
		}
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setDisplayHomeAsUpEnabled(true);
	}

	private void initView() {
		mProgressbar = findViewById(R.id.web_vieprogress);
		mErrorView = findViewById(R.id.web_view_layout_error_layout);
		mWebView = findViewById(R.id.web_view);
		mWebView.setWebViewClient(new MyWebViewClient());
		mWebView.setWebChromeClient(new MyWebChromeClient());
		mWebView.getSettings().setJavaScriptEnabled(true);
		mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
	}

	private String appendParams(String url) {
		StringBuilder info = new StringBuilder(url);
		if (url.charAt(url.length() - 1) == '&') {
			info.append("&");
		}
		String android_id = Settings.Secure.getString(getContentResolver(),
				Settings.Secure.ANDROID_ID);
		info.append("_aid").append(android_id);
		try {
			TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
			String device_id = tm.getDeviceId();
			info.append("_mid").append(device_id);
		} catch (Exception e) {
			// ignore it
		}

		info.append("_vn").append(NetTools.getVersionName(this));
		info.append("_vc").append(String.valueOf(NetTools.getVersionCode(this)));
		info.append("_ch").append(NetTools.getChannelNumber(this));
		info.append("_pn").append(getPackageName());

		info.append("&_bd=").append(NetTools.urlEncode(Build.BRAND));
		info.append("&_md=").append(NetTools.urlEncode(Build.MODEL));

		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();
		String net_type = "";
		if (ni != null) {
			switch (ni.getType()) {
			case ConnectivityManager.TYPE_WIFI:
				net_type = "wifi";
				break;
			case ConnectivityManager.TYPE_MOBILE:
				net_type = "mobile";
				break;
			default:
				net_type = "";
			}
		}
		info.append("&_nw=").append(net_type);
		info.append("&_ts=").append(System.currentTimeMillis());

		try {
			WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
			Point pt = new Point();
			wm.getDefaultDisplay().getSize(pt);
			String _wh = pt.x + "*" + pt.y;
			info.append("&_wh=").append(_wh);
		} catch (Exception e) {
			// ignore todo
		}

		LocationUtil lu = LocationUtil.getInstance(this);

		String longitude = NetTools.urlEncode(lu.getLongitude());
		String latitude = NetTools.urlEncode(lu.getLatitude());
		String city = NetTools.urlEncode(lu.getCity());
		if (!TextUtils.isEmpty(longitude)) {
			info.append("&_lg=").append(longitude);
		}
		if (!TextUtils.isEmpty(latitude)) {
			info.append("&_lt=").append(latitude);
		}

		if (!TextUtils.isEmpty(city)) {
			info.append("&_lc=").append(city);
		}
		return info.toString();
	}

	private boolean isDownloadLink(String url) {
		return url != null && url.startsWith(AppLinkParser.SCHEMA);
	}

	private void onAppClicked(String url) {
		AppLinkParser parser = new AppLinkParser(url);
		if (PackageUtils.isPackageInstalled(this, parser.getPkgName())) {
			try {
				Intent intent = getPackageManager().getLaunchIntentForPackage(parser.getPkgName());
				startActivity(intent);
			} catch (Exception e) {
				e.printStackTrace();
				Toast.makeText(this, "打开失败", Toast.LENGTH_SHORT).show();
			}
			return;
		}

		if (!parser.isValidStrict()) {
			Toast.makeText(this, "无法加入下载", Toast.LENGTH_SHORT).show();
			return;
		}
		String dlId = DownloadUtils
				.generateDownloadId(parser.getPkgName(), parser.getVersionCode());
		int status = getDownloadStatus(dlId, parser.getPkgName(), parser.getVersionCode());
		switch (status) {
		case DownloadService.STATUS_NO_STATUS: {
			addDownload(parser.getDlUrl(), parser.getName(), parser.getPkgName(),
					parser.getVersionName(), parser.getVersionCode(), parser.getMd5(),
					parser.getIconUrl(), parser.getSource());
			SuperActivityToast satoast = new SuperActivityToast(this, SuperToast.Type.BUTTON);
			satoast.setButtonText("查看");
			String info = parser.getName() + "已加入下载，点击右侧按钮可查看任务";
			if (!DownloadUtils.isMobileNetwork(this)) {
				satoast.setText(info);
				satoast.setDuration(SuperToast.Duration.LONG);
			} else {
				String gprs = "\n提示：" + getString(R.string.download_in_gprs);

				SpannableStringBuilder ssb = new SpannableStringBuilder(info + gprs);
				ssb.setSpan(new ForegroundColorSpan(Color.YELLOW), info.length(), ssb.length(),
						Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
				satoast.setText(ssb);
				satoast.setDuration(SuperToast.Duration.EXTRA_LONG);
			}
			satoast.setButtonIcon(R.drawable.download_icon);
			satoast.setOnClickWrapper(new OnClickWrapper("download_app",
					new SuperToast.OnClickListener() {
						@Override
						public void onClick(View view, Parcelable token) {
							startActivity(new Intent(WebViewActivity.this,
									DownloadManagerActivity.class));
						}
					}));
			satoast.show();
		}
			break;
		case DownloadService.STATUS_PAUSED_BY_ERROR:
		case DownloadService.STATUS_PAUSED_BY_MOBILE_NETWORK:
		case DownloadService.STATUS_PAUSED_BY_USER: {
			startDownload(dlId);
			SuperActivityToast satoast = new SuperActivityToast(this, SuperToast.Type.BUTTON);
			satoast.setButtonText("查看");
			String info = parser.getName() + "已恢复下载，点击右侧按钮可查看任务";
			if (!DownloadUtils.isMobileNetwork(this)) {
				satoast.setText(info);
				satoast.setDuration(SuperToast.Duration.LONG);
			} else {
				String gprs = "\n提示：" + getString(R.string.download_in_gprs);

				SpannableStringBuilder ssb = new SpannableStringBuilder(info + gprs);
				ssb.setSpan(new ForegroundColorSpan(Color.YELLOW), info.length(), ssb.length(),
						Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
				satoast.setText(ssb);
				satoast.setDuration(SuperToast.Duration.EXTRA_LONG);
			}
			satoast.setButtonIcon(R.drawable.download_icon);
			satoast.setOnClickWrapper(new OnClickWrapper("download_app",
					new SuperToast.OnClickListener() {
						@Override
						public void onClick(View view, Parcelable token) {
							startActivity(new Intent(WebViewActivity.this,
									DownloadManagerActivity.class));
						}
					}));
			satoast.show();
		}
			break;
		case DownloadService.STATUS_CAN_INSTALL:
			installApk(getDownloadById(dlId));
			break;
		case DownloadService.STATUS_DOWNLOAD_OUT_OF_DATE: {
			// removeDownloadImmediately(dlId);
			// removeDownloadFiles(parser.getDlUrl());

			removeOutofDateDownloads(parser.getPkgName());
			addDownload(parser.getDlUrl(), parser.getName(), parser.getPkgName(),
					parser.getVersionName(), parser.getVersionCode(), parser.getMd5(),
					parser.getIconUrl(), parser.getSource());
			SuperActivityToast satoast = new SuperActivityToast(this, SuperToast.Type.BUTTON);
			satoast.setButtonText("查看");
			String info = parser.getName() + "已加入下载，点击右侧按钮可查看任务";
			if (!DownloadUtils.isMobileNetwork(this)) {
				satoast.setText(info);
				satoast.setDuration(SuperToast.Duration.LONG);
			} else {
				String gprs = "\n提示：" + getString(R.string.download_in_gprs);

				SpannableStringBuilder ssb = new SpannableStringBuilder(info + gprs);
				ssb.setSpan(new ForegroundColorSpan(Color.YELLOW), info.length(), ssb.length(),
						Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
				satoast.setText(ssb);
				satoast.setDuration(SuperToast.Duration.EXTRA_LONG);
			}
			satoast.setButtonIcon(R.drawable.download_icon);
			satoast.setOnClickWrapper(new OnClickWrapper("download_app",
					new SuperToast.OnClickListener() {
						@Override
						public void onClick(View view, Parcelable token) {
							startActivity(new Intent(WebViewActivity.this,
									DownloadManagerActivity.class));
						}
					}));
			satoast.show();
		}
			break;
		default:
			break;
		}
	}

	private class MyWebChromeClient extends WebChromeClient {
		@Override
		public void onProgressChanged(WebView view, int newProgress) {
			super.onProgressChanged(view, newProgress);
			mProgressbar.setProgress(newProgress);
		}
	}

	private class MyWebViewClient extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			if (URLUtil.isNetworkUrl(url)) {
				if (url.indexOf("_rec=") != -1) {
					return super.shouldOverrideUrlLoading(view, appendParams(url));
				}
			} else if (isDownloadLink(url)) {
				onAppClicked(url);
				return true;
			}
			return super.shouldOverrideUrlLoading(view, url);
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			super.onPageStarted(view, url, favicon);
			mProgressbar.setVisibility(View.VISIBLE);
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			mProgressbar.setVisibility(View.GONE);
		}

		@Override
		public void onReceivedError(WebView view, int errorCode, String description,
				String failingUrl) {
			showErrorView();
			LogUtil.d(TAG, "onReceivedError");
		}
	}

	private void showErrorView() {
		mWebView.setVisibility(View.GONE);
		mProgressbar.setVisibility(View.GONE);
		mErrorView.setVisibility(View.VISIBLE);
		mErrorView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!TextUtils.isEmpty(mInitUrl)) {
					mErrorView.setOnClickListener(null);
					mErrorView.setVisibility(View.GONE);
					mWebView.setVisibility(View.VISIBLE);
					mProgressbar.setVisibility(View.VISIBLE);
					mWebView.loadUrl(mInitUrl);
				}
			}
		});
	}

	private void initContent() {
		if (!TextUtils.isEmpty(mInitUrl)) {
			mErrorView.setOnClickListener(null);
			mErrorView.setVisibility(View.GONE);
			mWebView.setVisibility(View.VISIBLE);
			mProgressbar.setVisibility(View.VISIBLE);
			mWebView.loadUrl(mInitUrl);
		} else {
			// do nothing
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.web_view, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			goBack();
			finish();
			break;
		case R.id.action_refresh:
			mWebView.reload();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (mWebView.canGoBack()) {
				mWebView.goBack();
				return true;
			}
			goBack();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void goBack() {
		AppMarketApplication app = (AppMarketApplication) getApplication();
		if (app.isAppRunning()) {
			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.addCategory(Intent.CATEGORY_LAUNCHER);
			intent.setClass(this, MainActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
					| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
			startActivity(intent);
		} else {
			Intent intent = new Intent(this, MainActivity.class);
			startActivity(intent);
		}
		finish();
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	public void onClick(View v) {
	}

}
